import PropTypes from 'react-router/lib/PropTypes'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Immutable from 'immutable'
import * as SettingAction from '../actions/setting'
import objectAssign from 'object-assign'
// import forEach from 'lodash/forEach'
import isArray from 'lodash/isArray'
import {WeaTable} from 'comsRedux'
import { WeaErrorPage, WeaTools } from 'ecCom'
import {Row,Col,Input,Tabs,Button,Alert,Spin,Icon,Form,Modal,Switch} from 'antd';
import { WeaSearchGroup,WeaTop,WeaTab,WeaRightMenu ,WeaInput,WeaSelect} from 'ecCom';
import BasicSetting from './Setting/BasicSetting/index'
import ShareSetting from './Setting/ShareSetting/index'
import MouldSetting from './Setting/MouldSetting/index'
import '../css/setting.css'

import { WeaRichText } from 'ecCom'

import * as Util from '../util/index'

//import WeaCkEditor from "./Component/wea-ckeditor/CKEAppend"
const WeaTableAction = WeaTable.action;
const FormItem = Form.Item;
const createForm = Form.create;
const confirm = Modal.confirm;

let ___this = null;

class Setting extends React.Component {
	static contextTypes = {
		router: PropTypes.routerShape
	}
	constructor(props) {
		super(props);
		_this = this;
		this.state={
			show:false,
			showModal:false,
			check:true,
			editmoudle:false,
			totalmodal:false,
			realId:'',
			msSelectedRowKeys:'',
			moudledefaultid:'',
			test:false,
			showModals:false,
			editid:false,
			shareId:0,
			selectsharetype:1,

		}
		this.CKE_ID = "wea_ckeditor_weibo_setting"
	}
	componentDidMount() {
		//一些初始化请求
		const { actions } = this.props;
		actions.getUserBlogBaseSetting();
		// actions.getUserBlogTemplateShareCondition();//个人模版设置--高级查询条件
	}
	componentWillReceiveProps(nextProps) {
		const keyOld = this.props.location.key;
		const keyNew = nextProps.location.key;
		//点击菜单路由刷新组件
		if(keyOld !== keyNew) {

		}
		
		if (this.props.moudleinfo !== nextProps.moudleinfo) {
            this.setState({check: nextProps.moudleinfo.BlogTemplateBean&&nextProps.moudleinfo.BlogTemplateBean.isUsed?true:false});
        }
		//设置页标题
		//		if(window.location.pathname.indexOf('/') >= 0 && nextProps.title && document.title !== nextProps.title)
		//			document.title = nextProps.title;
	}
	shouldComponentUpdate(nextProps, nextState) {
		//组件渲染控制
		//return this.props.title !== nextProps.title
		return true;
	}
	componentWillUnmount() {
		//组件卸载时一般清理一些状态
		const { actions} = this.props;
		actions.changeTab(0);
		this.setState({moudledefaultid:''});
	}
	render() {
		const { loading,spinning,ckvalue,title,tabkey,tabDatas,checked,moudleShareSessionkey,preview,previewinfo,showSearchAd,moudleinfo,sharinginfos,shareSessionkey,moudleSessionkey,actions,shareinfo,info,comsWeaTable} = this.props;
		const btns = this.getBtns();
		const {showModal,check,editmoudle,totalmodal,realId,moudledefaultid} = this.state;
		const {getFieldProps,getFieldsValue} = this.props.form;
        // if(moudleinfo.BlogTemplateBean&&moudleinfo.BlogTemplateBean.tempContent){
        // 	if (this.state.showModal&&this.refs[this.CKE_ID]) {
        //         let {setData} = this.refs[this.CKE_ID];
        //         const {moudleinfo} = this.props;
        //         setData(moudleinfo.BlogTemplateBean&&moudleinfo.BlogTemplateBean.tempContent);
        //     } else {
        //     }
        // }
        let values = getFieldsValue();
        const shareTablekey = shareSessionkey ? shareSessionkey.split('_')[0] : 'init';
		const shareTableNow = comsWeaTable.get(shareTablekey);
		const loadingTable = shareTableNow.get('loading');
        const shareSelectedRowKeys = shareTableNow.get('selectedRowKeys');

		const moudleShareTablekey = moudleShareSessionkey ? moudleShareSessionkey.split('_')[0] : 'init';
		const moudleShareTableNow = comsWeaTable.get(moudleShareTablekey);
        const msSelectedRowKeys = moudleShareTableNow.get('selectedRowKeys');

		const footer=[
            <Button key="back" type="ghost" size="large" onClick={()=>{this.setState({showModal:false,check:true});this.props.form.resetFields();this.props.actions.saveckvalue();}}>返 回</Button>,
            <Button key="submit" type="primary" size="large" onClick={this.saveMoudle.bind(this)}>
              保 存
            </Button>]
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 10 },
        };
        const formItemLayout2 = {
            labelCol: { span: 4 },
            wrapperCol: { span: 19 },
        };
		return (
			<div className='wea-blog-setting' style={{height:"100%",overflow:"hidden"}}>
				<WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)} style={{height:'100%'}}>
				<WeaTop 
            	loading={loading} 
            	icon={<span className='icon-coms-blog'/>} 
            	iconBgcolor="#6d3cf7"
            	title={title}  
            	buttons={btns}
	            showDropIcon={true}
	            dropMenuDatas={this.getRightMenu()}
                onDropMenuClick={this.onRightMenuClick.bind(this)}
            	/>
            	<WeaTab
		            selectedKey={tabkey}
		            datas={tabDatas}
		            keyParam='key'
		            onChange={this.changeTab.bind(this)}
		            searchType={tabkey==2?['base','advanced']:''}
                    searchsBaseValue={this.props.orderFields.tempName?this.props.orderFields.tempName.value:''}
		            setShowSearchAd={bool=>{this.props.actions.setShowSearchAd(bool)}}
            		hideSearchAd={()=> this.props.actions.setShowSearchAd(false)}
            		buttonsAd={this.getTabButtonsAd()}
            		showSearchAd={showSearchAd}
		            searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
		            onSearch={this.doSearch.bind(this)}
                    onSearchChange={v=>{actions.saveOrderFields({tempName:{name:'tempName',value:v}})}}
		        />
		        {tabkey==0?
		        <BasicSetting style={{display: tabkey==0 ?'block':'none'}}  checked={checked} onChange={this.changeSwitch.bind(this)}/>
		        :tabkey==1?
		        <ShareSetting style={{display: tabkey==1 ?'block':'none'}} ref="ShareSetting" states={this.state} selectedRowKeys={shareSelectedRowKeys && shareSelectedRowKeys.toJS()} all={this.props} shareinfo={shareinfo} actions={actions} sharinginfos={sharinginfos} sessionkey={shareSessionkey} loading={loading}/>
		        :
		        <MouldSetting style={{display: tabkey==2 ?'block':'none'}} selectedRowKeys={msSelectedRowKeys&&msSelectedRowKeys.toJS()} realId={realId} spinning={spinning} moudleShareSessionkey={moudleShareSessionkey} showtotalmodal={totalmodal} data={previewinfo} all={this.props} loading={loading} changeState={(e)=>this.changeState(e)} changeStatet={(e)=>this.changeStatet(e)} changeStater={(e)=>this.changeStater(e)} showModal={preview} onOperatesClickt={this.onOperatesClickt.bind(this)} sessionkey={moudleSessionkey} actions={actions}/>
		        }
            	<Modal
                    title={editmoudle?'编辑模板':'新建模板'}
                    wrapClassName="vertical-center-modal blogsettingmmodal-vertical-center"
                    visible={showModal}
                    footer={footer}
                    maskClosable={false}
                    className={`blogsettingmmodal`}
                    onCancel={()=>{this.setState({showModal:false,check:true});this.props.form.resetFields();this.props.actions.saveckvalue();}}
                >
                <div className="icon-circle-base blogsettingmodal-modal"  style={{backgroundColor:'#6d3cf7'}}>
                	<span className='icon-coms-blog' />
                </div>

                <Row className="">
                    <Form horizontal>
                        <FormItem
                          {...formItemLayout}
                          label="模版名称"
                        >
                        	<WeaInput viewAttr={3} {...getFieldProps('tempName2',{
                        							  initialValue:editmoudle?moudleinfo.BlogTemplateBean&&moudleinfo.BlogTemplateBean.tempName:'',
												      rules: [
												        { required: true,message: '模板名称必须输入' },
												      ],
												    })}/>
                        </FormItem>
                        <FormItem
                          {...formItemLayout}
                          label="模板描述"
                        >
                        	<WeaInput viewAttr={2} {...getFieldProps('tempDesc2',{
                        								initialValue:editmoudle?moudleinfo.BlogTemplateBean&&moudleinfo.BlogTemplateBean.tempDesc:''
                        							})}/>
                        </FormItem>
                    	<FormItem
                          {...formItemLayout}
                          label="状态"
                        >
                        	<Switch style={{marginTop:'5px'}} checked={check} onChange={this.changeMoudleSwitch.bind(this)} />
                        </FormItem>
                    	<FormItem
                          {...formItemLayout2}
                          label="模版内容"
                          style={{height:'400px',overflow:'auto',marginBottom:'0'}}
                        >
                    		<div className='wea-ckeditor-import-ecCom'>
	                        	<WeaRichText 
				            		id={this.CKE_ID}
				                    ref={this.CKE_ID}
				                    value={ckvalue}
				                    ckConfig={{
				                    	toolbar:[
								            { name: 'document', items: [ 'Source'] },
								            { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
								            { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
								            { name: 'colors', items: [ 'TextColor' ] },
								            { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
								            { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] }
								        ],
				                        height: 260,
				                        uploadUrl: '/api/blog/fileupload/uploadimage',
				                    }}
				                    extentsConfig
				                    bottomBarConfig
				                    onChange={v=>{actions.saveckvalue(v)}}
				                    onStatusChange={s => {}}
				                    onToolsChange={Util.transfStr}
				            	/>
			            	</div>
                        </FormItem>
                    </Form>
                </Row>

                </Modal>
                </WeaRightMenu>
            </div>
		)
	}
	getRightMenu(){
		
    	const {actions,tabkey,moudleSessionkey,comsWeaTable,shareSessionkey} = this.props;
    	const {moudledefaultid,test} = this.state;
    	const moudleTablekey = moudleSessionkey ? moudleSessionkey.split('_')[0] : 'init';
		const moudleTableNow = comsWeaTable.get(moudleTablekey);
        const moudleSelectedRowKeys = moudleTableNow.get('selectedRowKeys');
        const shareTablekey = shareSessionkey ? shareSessionkey.split('_')[0] : 'init';
		const shareTableNow = comsWeaTable.get(shareTablekey);
        const shareSelectedRowKeys = shareTableNow.get('selectedRowKeys');
    	let btns = [];
    	if(tabkey==0){
			btns.push({
    		key: 1,
    		icon: <i className='icon-coms-Preservation'/>,
    		content:'保存',
    		disabled:test?false:true
    		});
    	}
    	if(tabkey==1){
			btns.push({
    		key: 2,
    		icon: <i className='icon-coms-New-Flow'/>,
    		content:'新建'
    		});
    		btns.push({
    		key: 3,
    		icon: <i className='icon-coms-Batch-delete'/>,
    		content:'批量删除',
    		disabled:shareSelectedRowKeys.toJS().length?false:true
    		});
    		btns.push({
    		key: 4,
    		icon: <i className='icon-coms-Custom'/>,
    		content:'显示定制列'
    		});
    	}
    	if(tabkey==2){
    		btns.push({
    		key: 1,
    		icon: <i className='icon-coms-Preservation'/>,
    		content:'保存',
    		disabled:moudledefaultid?false:true
    		});
    		btns.push({
    		key: 2,
    		icon: <i className='icon-coms-New-Flow'/>,
    		content:'新建'
    		});
    		btns.push({
    		key: 3,
    		icon: <i className='icon-coms-Batch-delete'/>,
    		content:'批量删除',
    		disabled:moudleSelectedRowKeys.toJS().length?false:true
    		});
			btns.push({
    		key: 4,
    		icon: <i className='icon-coms-Custom'/>,
    		content:'显示定制列'
    		});
    		btns.push({
    		key: 5,
    		icon: <i className='icon-coms-search'/>,
    		content:'搜索'
    		});
    	}
    	return btns;
	}
	onRightMenuClick(key){
    	const {tabkey,actions,moudleSessionkey,shareSessionkey,comsWeaTable} = this.props;
    	const shareTablekey = shareSessionkey ? shareSessionkey.split('_')[0] : 'init';
		const shareTableNow = comsWeaTable.get(shareTablekey);
        const shareSelectedRowKeys = shareTableNow.get('selectedRowKeys');

    	if(tabkey==0){
    		this.save();
    	}
    	if(tabkey==1){
    		if(key==2){
    			this.setState({showModals:true,editid:false,shareId:0,selectsharetype:1})
    		}
    		if(key==3){
                this.refs.ShareSetting.showConfirm(shareSelectedRowKeys.toJS());
    		}
    		if(key==4){
    			actions.setColSetVisible(shareSessionkey,true);
    			actions.tableColSet(shareSessionkey,true)
    		}
    	}
    	if(tabkey==2){
    		if(key==1){
    			this.add();
    		}
    		if(key==2){
    			this.build();
    		}
    		if(key==3){
    			this.delete();
    		}
    		if(key==4){
    			actions.setColSetVisible(moudleSessionkey,true);
    			actions.tableColSet(moudleSessionkey,true)
    		}
    		if(key==5){
    			this.doSearch('v');
    		}
    	}
    }
	changeState(e){
		const {actions} = this.props;
		actions.setPreviewShow(e);
	}
	changeStatet(e){
		this.setState({totalmodal:e});
	}
	changeStater(e){
		this.setState({moudledefaultid:e});
	}
	onOperatesClickt(record,index,operate,flag){
        const {actions} = this.props;
        if(flag == 0){
            actions.getBlogTempleteInfoById({btId:record.realId,this:this});
            this.setState({showModal:true,editmoudle:true})
        }
        if(flag == 1){
        	actions.setPreview({btId:record.realId})
        	
        }
        if(flag == 2){
        	actions.getUserBlogTemplateShareTable({tempid:record.realId});
			this.setState({totalmodal:true,realId:record.realId});
        }
        if(flag == 3){
            this.showConfirm(record.realId);
            // actions.deleteBlogTemplateByIds({tempIds:record.realId});
        }
    }
    showConfirm(e) {
        const {selectedRowKeys,actions} = this.props;
        confirm({
            title: '您是否确认要删除这项内容',
            content: '',
            onOk() {
                    actions.deleteBlogTemplateByIds({tempIds:e});
            },
            onCancel() {},
        });
    }
	
	saveMoudle(){
		this.props.form.validateFields((errors, values) => {
	    if (!!errors) {
	        return;
	    }
	    const {actions,moudleinfo} = this.props;
        let tempid = moudleinfo.BlogTemplateBean?moudleinfo.BlogTemplateBean.id:0;
		
		const {getFieldsValue,getFieldValue} = this.props.form;
		let value = getFieldsValue();
		value = objectAssign({},{tempid:tempid,tempName:getFieldValue('tempName2'),tempDesc:getFieldValue('tempDesc2'),isUsed:this.state.check?1:0,isSystem:0,tempContent:this.refs[this.CKE_ID].getData()});
		actions.saveOrUpdateBlogTemplate(value);
		this.setState({showModal:false});
		this.props.form.resetFields();
        this.props.actions.saveckvalue()
    	});
		
	}
	changeSwitch(checked){
		const {actions} = this.props;
		actions.changeChecked(checked);
		this.setState({test:true});
	}
	changeMoudleSwitch(checked){
		const {actions} = this.props;
		this.setState({check:checked});
	}
	getBtns(){
		const { tabkey,moudleSessionkey,comsWeaTable} = this.props;
		const {moudledefaultid,test} = this.state;
		const moudleTablekey = moudleSessionkey ? moudleSessionkey.split('_')[0] : 'init';
		const moudleTableNow = comsWeaTable.get(moudleTablekey);
        const moudleSelectedRowKeys = moudleTableNow.get('selectedRowKeys');
		if(tabkey==0){
			return [(<Button type="primary" disabled={test?false:true} onClick={this.save.bind(this)}>保存</Button>)];
		}
		if(tabkey==1){
			return [];
		}
		if(tabkey==2){
			return [
					(<Button type="primary" disabled={moudledefaultid?false:true} onClick={this.add.bind(this)}>保存</Button>),
					(<Button type="primary" onClick={this.build.bind(this)}>新建</Button>),
					(<Button type="primary" disabled={moudleSelectedRowKeys.toJS().length?false:true} onClick={this.delete.bind(this)}>批量删除</Button>),
				   ];
			}
	}
	getTabButtonsAd(){
		const {actions} = this.props;
        return [
            (<Button type="primary" onClick={()=>this.doSearch()}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.saveOrderFields({})}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
	}
	doSearch(v){
    	const {actions} = this.props;
    	if(!!v){
    		//快速搜索
    		const value = this.props.orderFields;
	    	let tempName = value.tempName?value.tempName.value:'';
	    	actions.getUserBlogTemplateTable({tempName:tempName});//模版设置--列表
    	}else{
    		//高级搜索
    		actions.setShowSearchAd(false);//高级搜索是否显示
	    	const value = this.props.orderFields;
	    	let tempName = value.tempName?value.tempName.value:'';
	    	let tempDesc = value.tempDesc?value.tempDesc.value:'';
	    	let isSystem = value.isSystem?value.isSystem.value:'';
	    	actions.getUserBlogTemplateTable({tempName:tempName,tempDesc:tempDesc,isSystem:isSystem});//模版设置--列表
    	}
    	
    	
    }
	getSearchs() {
        return <WeaSearchGroup showGroup={true} needTigger={true} title="常用条件" items={this.getFields()} />
    }
	
	save(){
		const { actions,checked } = this.props;
		let checkeds = checked==true ? 1:0;
		actions.saveBlogUserSetting({isReceive:checkeds});
	}

	delete(){
		const { actions,moudleSessionkey,comsWeaTable } = this.props;
		const moudleTablekey = moudleSessionkey ? moudleSessionkey.split('_')[0] : 'init';
		const moudleTableNow = comsWeaTable.get(moudleTablekey);
        const moudleSelectedRowKeys = moudleTableNow.get('selectedRowKeys');
		values = moudleSelectedRowKeys.toJS();
        this.showConfirm(values);

		// actions.deleteBlogTemplateByIds({tempIds:values});
	}

	build(){
		const { actions } = this.props;
		this.setState({showModal:true,editmoudle:false,check:true},()=>{
//			if (this.state.showModal&&this.refs[this.CKE_ID]) {
//              let {CreateEditor} = this.refs[this.CKE_ID]
//              CreateEditor("")
//          } else {
//          	this.refs[this.CKE_ID].RemoveEditor()
//          }
		})
	}

	add(){
		//保存模板
		const { actions} = this.props;
		const {moudledefaultid} = this.state;
		actions.setUserBlogTemplateToDefault({defaultBtId:moudledefaultid});
	}

	getFields(){
		const fieldsData = this.props.info;
		let items = [];
        isArray(fieldsData) && fieldsData.forEach((field) => {
            items.push({
                com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                    	{WeaTools.getComponent(field.conditionType, field.browserConditionParam, field.domkey, this.props,field)}
                    </FormItem>),
                colSpan:1
            })
        })
        return items;
	}

	//切换tab
	changeTab(e){
		const { actions } = this.props;
		actions.changeTab(e);
		if(e==0){
			this.setState({moudledefaultid:'',showModals:false});
			actions.getUserBlogBaseSetting();
		}
		if(e==1){
			actions.getFixedSharingInfos();//获取上级和指定分享信息
			actions.getBlogShareTable()//获取我的分享设置表格
			this.setState({moudledefaultid:'',test:false});
		}
		if(e==2){
			actions.getUserBlogTemplateShareCondition();//个人模版设置--高级查询条件
			actions.getUserBlogTemplateTable();//模版设置--列表
			this.setState({test:false,showModals:false});

		}
	}
}

// form 表单与 redux 双向绑定
Setting = Form.create({
	onFieldsChange(props, fields) {
		props.actions.saveOrderFields({...props.orderFields,...fields});
	},
	mapPropsToFields(props) {
		return props.orderFields;
	}
})(Setting);


//组件检错机制
class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return(
			<WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
		);
	}
}

Setting = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(Setting);

// 把 state map 到组件的 props 上
const mapStateToProps = state => {
	const { loading, title } = state.blogSetting;
	const { comsWeaTable } = state;
	return { ...state.blogSetting,comsWeaTable }
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
	return {
		actions: bindActionCreators({...SettingAction,...WeaTableAction}, dispatch)
	}
}

export default connect(mapStateToProps, mapDispatchToProps)(Setting);